package cn.etgps.etgps.ui;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.umeng.update.UmengUpdateAgent;

import cn.etgps.etgps.R;
import cn.etgps.etgps.base.BaseActivity;
import cn.etgps.etgps.blmanager.BaseBLManager;
import cn.etgps.etgps.blmanager.UserManager;
import cn.etgps.etgps.dataEntity.LoginBean;
import cn.etgps.etgps.dialog.DialogCreater;
import cn.etgps.etgps.utils.Constant;

/**
 * 登陆
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {
    /**
     * 用户名
     */
    private EditText mUserName = null;
    /**
     * 用户密码
     */
    private EditText mUserPassword = null;
    /**
     * 是否记住密码
     */
    private CheckBox mRememberPass = null;
    private ImageView mUserNameClose = null;
    private ImageView mPasswordClose = null;
    TextWatcher mTextWatcher = new TextWatcher() {
        @Override
        public void afterTextChanged(Editable s) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {


        }

        @Override
        public void onTextChanged(CharSequence str, int start, int before, int count) {
            if (!mUserName.getText().toString().trim().equals("")) {
                mUserNameClose.setVisibility(View.VISIBLE);
            } else {
                mUserNameClose.setVisibility(View.GONE);
            }

            if (!mUserPassword.getText().toString().trim().equals("")) {
                mPasswordClose.setVisibility(View.VISIBLE);
            } else {
                mPasswordClose.setVisibility(View.GONE);
            }
        }
    };
    private UserManager mUserManger = null;
    /**
     * 登陆对象
     */
    private LoginBean mLoginBean = null;
    /**
     * 用户名字符串
     */
    private String mName = null;
    /**
     * 用户密码字符串
     */
    private String mPassword = null;
    /**
     * 登陆线程
     */
    private UserLoginTask mUserLoginTask = null;
    /**
     * 登陆
     */
    private Button mLoginBtn = null;
    /**
     * 设置ip，port
     */
    private LinearLayout mSystemSet = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        //版本更新检查
        if (BaseBLManager.checkNetwork(this)) {
            //友盟更新 start
            UmengUpdateAgent.setUpdateOnlyWifi(false);
            UmengUpdateAgent.update(this);
            UmengUpdateAgent.setUpdateCheckConfig(false);
            //友盟更新 end
        }
    }

    private void initView() {
        mUserManger = new UserManager(this);
        mLoginBtn = (Button) findViewById(R.id.login_btn);
        mLoginBtn.setOnClickListener(this);
        mSystemSet = (LinearLayout) findViewById(R.id.system_set);
        mSystemSet.setOnClickListener(this);
        mUserName = (EditText) findViewById(R.id.account_text);
        mUserPassword = (EditText) findViewById(R.id.password_text);
        mRememberPass = (CheckBox) findViewById(R.id.radioButton);
        mUserNameClose = (ImageView) findViewById(R.id.account_close);
        mPasswordClose = (ImageView) findViewById(R.id.password_close);
        mUserName.addTextChangedListener(mTextWatcher);
        mUserPassword.addTextChangedListener(mTextWatcher);
        mUserNameClose.setOnClickListener(this);
        mPasswordClose.setOnClickListener(this);
        initData();
    }

    private void initData() {
        String[] sp = mUserManger.getUserInfo();
        mUserName.setText(sp[0]);  //不管记住不记住 用户名都有
        String isRemember = sp[2];
        if (isRemember.equals("1")) { //表示选择记住
            mUserPassword.setText(sp[1]);
            mRememberPass.setChecked(true);
        } else {
            mRememberPass.setChecked(false);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login_btn:
                if (checkInput()) {
                    String name = mUserName.getText().toString().trim();
                    String password = mUserPassword.getText().toString().trim();
                    mLoginBean = new LoginBean();
                    //首先进行网络判断
                    if (mUserManger.checkNetwork(this)) {
                        if (mUserLoginTask != null && mUserLoginTask.getStatus() == AsyncTask.Status.RUNNING) {
                            mUserLoginTask.cancel(true);
                        }
                        //在登陆判断
                        mUserLoginTask = new UserLoginTask();
                        mUserLoginTask.execute(name, password);
                    } else {
                        mUserManger.showToastMessage(getString(R.string.toast_no_network), 1000);
                    }
                }
                break;
            case R.id.account_close:
                mUserName.setText("");
                break;
            case R.id.password_close:
                mUserPassword.setText("");
                break;
            case R.id.system_set:
                Intent intent = new Intent(LoginActivity.this, SystemSet.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    /**
     * 检测输入
     */
    public boolean checkInput() {
        mName = mUserName.getText().toString().trim();
        mPassword = mUserPassword.getText().toString().trim();
        if (null == mName || mName.trim().isEmpty() || mName.length() == 0) {
            mUserManger.showToastMessage(getString(R.string.acconunt_is_null), 1000);
            return false;
        }
        if (null == mPassword || mPassword.trim().isEmpty() || mPassword.length() == 0) {
            mUserManger.showToastMessage(getString(R.string.password_is_null), 1000);
            return false;
        }
        return true;
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            try {
                this.showNormalDialog(DialogCreater.DIALOG_EXIT);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return false;
        }
        return super.dispatchKeyEvent(event);
    }

    /**
     * 登陆异步访问网络接口
     */
    public class UserLoginTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            showNormalDialog(DialogCreater.DIALOG_PROGRESS);
            return mUserManger.login(params, mLoginBean);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            //成功 记录登陆信息
            if (s.equals(Constant.RETURN_RESULT_OK)) {
                String[] saveInfo = new String[5];
                saveInfo[0] = mName;
                saveInfo[1] = mLoginBean.getUser_id();
                saveInfo[2] = mLoginBean.getUser_type();
                saveInfo[3] = mPassword;
                String isRemember = "";
                if (mRememberPass.isChecked()) {
                    isRemember = "1";
                } else {
                    isRemember = "0";
                }
                saveInfo[4] = isRemember;
                mUserManger.saveUserLoginBasicInfo(saveInfo);
                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                finish();
            } else {
                mUserManger.showToastMessage(getString(R.string.login_error), 1000);
            }
            dismissNormalDialog();
        }
    }
}
